import Vue from 'vue'
import { loginFunc, getInfo } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'
import router from '@/router';
import Cookie from 'js-cookie'
import store from '../index.js'
import { asyncRouterMap } from '@/config/router.config.js'
const user = {
  state: {
    school: '',
    id: '',
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {},
    school_name: '',
    default_school_id:null,
    isForm:true
  },

  mutations: {
    changeFrom(state){
      state.isForm=false
    },
    noChangeFrom(state){
      state.isForm=true
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_SCHOOL: (state, school) => {
      state.school = school
    },
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_SCHOOL_NAME: (state, school_name) => {
      state.school_name = school_name
    },
    SET_USER: (state) => {
      state = {}
    },
    SET_DEFAULT_SCHOOL:(state,default_school_id)=>{
      state.default_school_id = default_school_id
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        loginFunc(userInfo).then(response => {
          Vue.ls.set(ACCESS_TOKEN, response.access_token, 7 * 24 * 60 * 60 * 1000)
          commit('SET_TOKEN', response.access_token)
          // commit('SET_DEFAULT_SCHOOL',response)
          Cookie.set('token_', response.token_type + ' ' + response.access_token)
          // Cookie.set('overDueTime', parseInt(new Date().getTime() / 1000) + parseInt(response.expires_in))
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo({school_id:store.state.user.school||undefined}
        ).then(response => {
          let result = JSON.parse(JSON.stringify(response))
          commit('SET_NAME', { name: result.name, welcome: welcome() })
          if (result.avatar && result.avatar.url) {
            commit('SET_AVATAR', result.avatar.url)
          }
          commit('SET_ID', result.id)
          if (!store.state.user.school) {
            commit('SET_SCHOOL', Number(result.default_school_id) || (result.schools instanceof Array && result.schools[0].id))
            result.schools.forEach(item => {
              if (item.id == result.default_school_id) {
                commit('SET_SCHOOL_NAME', item.name)
              } else {
                commit('SET_SCHOOL_NAME', result.schools instanceof Array && result.schools[0].name)
              }
            })
          } else {
            commit('SET_SCHOOL', store.state.user.school)
            result.schools.forEach(item => {
              if (item.id == result.default_school_id) {
                commit('SET_SCHOOL_NAME', item.name)
              } else {
                if(item.id==store.state.user.school){
                  commit('SET_SCHOOL_NAME', item.name)
                }
              }
            })
          }
          let arr = result.role.permissions
          arr.forEach(val => {
            val.actions = '[{"action":"add","defaultCheck":false,"describe":"新增"},{"action":"query","defaultCheck":false,"describe":"查询"},{"action":"get","defaultCheck":false,"describe":"详情"},{"action":"update","defaultCheck":false,"describe":"修改"},{"action":"delete","defaultCheck":false,"describe":"删除"}]'
            val.actionEntitySet = [{
              action: 'add',
              describe: '新增',
              defaultCheck: false
            }, {
              action: 'query',
              describe: '查询',
              defaultCheck: false
            }, {
              action: 'get',
              describe: '详情',
              defaultCheck: false
            }, {
              action: 'update',
              describe: '修改',
              defaultCheck: false
            }, {
              action: 'delete',
              describe: '删除',
              defaultCheck: false
            }],
              val.actionList = null,
              val.dataAccess = null
          })
          const roleObj = {
            permissions: arr
            // [{
            //   roleId: 'admin',
            //   permissionId: 'dashboard',
            //   permissionName: '中心首页',
            //   actions: '[{"action":"add","defaultCheck":false,"describe":"新增"},{"action":"query","defaultCheck":false,"describe":"查询"},{"action":"get","defaultCheck":false,"describe":"详情"},{"action":"update","defaultCheck":false,"describe":"修改"},{"action":"delete","defaultCheck":false,"describe":"删除"}]',
            //   actionEntitySet: [{
            //     action: 'add',
            //     describe: '新增',
            //     defaultCheck: false
            //   }, {
            //     action: 'query',
            //     describe: '查询',
            //     defaultCheck: false
            //   }, {
            //     action: 'get',
            //     describe: '详情',
            //     defaultCheck: false
            //   }, {
            //     action: 'update',
            //     describe: '修改',
            //     defaultCheck: false
            //   }, {
            //     action: 'delete',
            //     describe: '删除',
            //     defaultCheck: false
            //   }],
            //   actionList: null,
            //   dataAccess: null
            // }]
          }
          result.role = roleObj
          if (result.role && result.role.permissions && result.role.permissions.length > 0) {
            const role = result.role
            role.permissions = result.role.permissions
            role.permissions.map(per => {
              if (per.actionEntitySet != null && per.actionEntitySet.length > 0) {
                const action = per.actionEntitySet.map(action => { return action.action })
                per.actionList = action
              }
            })
            role.permissionList = role.permissions.map(permission => { return permission.permissionId })
            commit('SET_ROLES', result.role)
            commit('SET_INFO', result)
          } else {
            resolve(result)
          }
          commit('SET_NAME', { name: result.name, welcome: welcome() })
          resolve(result)
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        commit('SET_USER')
        Cookie.remove('token_')
        Vue.ls.remove(ACCESS_TOKEN)
        window.sessionStorage.clear()
        router.push({ path: '/user/login' })
        resolve()
      })
    },


  }
}

export default user
